use tera::Context;
use serde_json::json;
use actix_session::Session;
use actix_web::{
    get, post, Result, Responder,
    web::Query
};
use crate::rules::Vo;
use crate::util::{ctx, redirect, to_json_list};
use crate::users::dao as userDao;
use crate::system::dao as systemDao;
use crate::market::dao as marketDao;

// 跳转到交路排班菜单页
#[get("/routeList.html")]
pub async fn route_list(session: Session) -> impl Responder {
    let vo = Vo{data: map!{"statu"=>String::from("1")}};
    let mut context = Context::new();
    context.insert("trains", &(systemDao::train_list("name", &vo)));
    
    render!("market/routeList.html", &ctx(context, &session))
}

// 查询交路排班信息
#[get("/routeData.html")]
pub async fn route_data(data: Query<Vo>) -> Result<impl Responder> {
    let vo = data.into_inner();
    let cols = "id,name,trains,workDate,quitDate";
    let count = marketDao::route_count(&vo);
    let list = marketDao::route_list(&cols, &vo);
    
    return Ok(to_json_list(map!{"code"=>json!("20"), "count"=>json!(&count), "list"=>json!(&list)}));
}

// 编辑交路排班信息
#[get("/editRoute.html")]
pub async fn edit_route(session: Session, data: Query<Vo>) -> impl Responder {
    let mut context = Context::new();
    if data.blank("id") {
        let vo = Vo{data: map!{"statu"=>String::from("1")}};
        context.insert("trains", &(systemDao::train_list("id,name,days", &vo)));
    } else {
        context.insert("bo", &(marketDao::get_route("id,userId,name,trains,days,workDate,quitDate", data.long("id"))));
    }
    let vo = Vo{data: map!{"job"=>String::from("销售")}};
    context.insert("users", &(userDao::user_list("id,name", &vo)));
    
    render!("market/editRoute.html", &ctx(context, &session))
}

// 保存交路排班信息
#[post("/saveRoute.html")]
pub async fn save_route(data: String) -> impl Responder {
    let json = urlencoding::decode(&data[5..]).unwrap();
    let list: Vec<Vo> = serde_json::from_slice(json.as_bytes()).unwrap();
    marketDao::save_route(list);

    redirect("../market/routeList.html")
}

// 打印交路排班信息
#[get("/printRoute.html")]
pub async fn print_route(session: Session) -> impl Responder {
    let vo = Vo{data: map!{"statu"=>String::from("1")}};
    let mut context = Context::new();
    context.insert("trains", &(systemDao::train_list("name", &vo)));
    
    render!("market/printRoute.html", &ctx(context, &session))
}
